<template>
<div>
聊天列表
<ul>
<li v-for="(i,index) in messlist" :key="index">{{i}}</li>
</ul>

<van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="sendmes"
          name="内容"
          label="内容"
          placeholder="内容"
          :rules="[{ required: true, message: '请填写内容' }]"
        />

      </van-cell-group>
      <div class="button-container">
        <van-button round block type="primary" native-type="submit" >
          提交
        </van-button>
      </div>
    </van-form>


</div>

</template>

<script setup>
import { ref,onMounted } from 'vue';
// import http from '../http';
import {useRoute}  from 'vue-router'


    const route = useRoute()

    const messlist=ref([])
    const sendmes=ref('')
    const socket = ref()

    const userid =route.query.id

    const onSubmit=()=>{
        socket.value.send(JSON.stringify({"room":'user'+userid,"mes":sendmes.value}))
    }

    const initwebsocket=()=>{
        var room = 'user'+userid
        socket.value = new WebSocket("ws://localhost:8000/room/"+room+"/");

        // 当客户端和服务端刚创建好连接(self.accept)之后，自动触发.
        socket.value.onopen =  ()=>{
            console.log("连接成功")
        }
        // 回调函数，客户端接收服务端消息
        socket.value.onmessage =  (event)=>{
            var data  = JSON.parse(event.data)

            messlist.value.push(data)
        }
    }

    onMounted(()=>{
        initwebsocket()
    })
</script>

<style scoped>

</style>